package com.prd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.prd.config.LoginInterceptor;
import com.prd.dto.SupervisorVo;
import com.prd.mapper.EntTaskPeriodicMapper;
import com.prd.model.EntTaskPeriodic;
import com.prd.model.LoginUser;
import com.prd.service.EntTaskPeriodicService;
import com.prd.util.UserInfoUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class EntTaskPeriodicServiceImpl extends ServiceImpl<EntTaskPeriodicMapper, EntTaskPeriodic> implements EntTaskPeriodicService {

    @Autowired
    private EntTaskPeriodicMapper entTaskPeriodicMapper;

    @Override
    public int insertInfo(EntTaskPeriodic entTaskPeriodic) {
        LambdaQueryWrapper<EntTaskPeriodic> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EntTaskPeriodic::getTaskId, entTaskPeriodic.getTaskId());
        queryWrapper.eq(entTaskPeriodic.getStageId() != null, EntTaskPeriodic::getStageId, entTaskPeriodic.getStageId());
        EntTaskPeriodic TaskPeriodic = entTaskPeriodicMapper.selectOne(queryWrapper);
        if (TaskPeriodic != null) {
            throw new RuntimeException("该记录已经存在！");
        }
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        BeanUtils.copyProperties(UserInfoUtil.recordInfo(loginUser.getId(), loginUser.getName(), true), entTaskPeriodic);
        return entTaskPeriodicMapper.insert(entTaskPeriodic);
    }

    @Override
    public int updateInfo(EntTaskPeriodic entTaskPeriodic) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        BeanUtils.copyProperties(UserInfoUtil.recordInfo(loginUser.getId(), loginUser.getName(), false), entTaskPeriodic);
        return entTaskPeriodicMapper.updateById(entTaskPeriodic);
    }

    @Override
    public int addSupervisor(SupervisorVo supervisorVo) {
        EntTaskPeriodic entTaskPeriodic = entTaskPeriodicMapper.selectById(supervisorVo.getId());
        if (entTaskPeriodic == null) {
            throw new RuntimeException("记录没有找到！");
        }
        entTaskPeriodic.setReach(supervisorVo.getReach());
        entTaskPeriodic.setGist(supervisorVo.getGist());
        entTaskPeriodic.setContent(supervisorVo.getContent());
        entTaskPeriodic.setRecord(supervisorVo.getRecord());
        entTaskPeriodic.setPicture(supervisorVo.getPicture());
        return updateInfo(entTaskPeriodic);
    }
}
